package com.zxl.yjb.activity.my;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zxl.yjb.R;
import com.zxl.yjb.activity.home.user.UserInfoActivity;
import com.zxl.yjb.activity.home.user.UserSpaceActivity;
import com.zxl.yjb.adapter.MyFriendsListAdapter;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.UserBean;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyFriendsActivity extends BaseActivity implements OnRefreshLoadMoreListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_page_title)
    TextView tvPageTitle;
    @BindView(R.id.rv_friends_list)
    RecyclerView rvFriendsList;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    private int currentPager = 1;
    private int pageSize = 20;
    private MyFriendsListAdapter adapter;

    private String origin = "";
    private String cat_id = "";
    private double longitude;
    private double latitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_friends);
        ButterKnife.bind(this);
        origin = getIntent().getStringExtra("origin");
        cat_id = getIntent().getStringExtra("cat_id");
        longitude = getIntent().getDoubleExtra("longitude",0);
        latitude = getIntent().getDoubleExtra("latitude",0);
        initView();
        initEvent();
        if ("Around".equals(origin))
        {
            adapter.setShowSelecteView(true);
            getAround4skill(false);
        }
        else if ("Friends".equals(origin))
        {
            adapter.setShowSelecteView(true);
            getFriendsSkillList(false);
        }
        else
        {
            getFriendsList(false);
        }

    }

    @Override
    protected void initView() {

        if ("Around".equals(origin)||"Friends".equals(origin))
        {
            tvConfirm.setText("确定");
        }
        else
        {
            tvConfirm.setText("编辑");
        }

        tvConfirm.setVisibility(View.VISIBLE);
        initAdapter();
        refreshLayout.setOnRefreshLoadMoreListener(this);
    }

    private void initAdapter() {
        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvFriendsList.setLayoutManager(layoutManager);
        //创建适配器
        if ("Around".equals(origin)||"Friends".equals(origin))
        {
            adapter = new MyFriendsListAdapter(R.layout.item_my_friends, "friends_list","nearby");
        }
        else
        {
            adapter = new MyFriendsListAdapter(R.layout.item_my_friends, "friends_list");
        }
        //给RecyclerView设置适配器
        rvFriendsList.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(MyFriendsActivity.this,UserSpaceActivity.class);
                intent.putExtra("uid",((UserBean)adapter.getItem(position)).getUid());
                startActivity(intent);
            }
        });

    }


    private void initEvent() {

    }

    /**
     * 获取好友列表
     *
     * @param isRefresh 是否为刷新
     */
    private void getFriendsList(final boolean isRefresh) {
        Map<String, String> map = new HashMap<>();
        map.put("page", currentPager + "");
        map.put("count", pageSize + "");
        map.put("attribute", "1");
        DataManager dataManager = new DataManager();
        ObserverOnNextListener<List<UserBean>> listener = new ObserverOnNextListener<List<UserBean>>() {
            @Override
            public void onNext(List<UserBean> detailBeanList) {
                currentPager++;
                if (isRefresh) {
                    adapter.setNewData(detailBeanList);
                    refreshLayout.finishRefresh();
                } else {
                    adapter.addData(detailBeanList);
                    refreshLayout.finishLoadMore();
                    if (detailBeanList.size() < pageSize) {
                        refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                    }
                }
            }
        };
        dataManager.friendsList(new ProgressObserver<List<UserBean>>(listener, this) {
            @Override
            public void showDialog() {
            }
        }, map);

    }

    /**
     * 获取好友列表
     *
     * @param isRefresh 是否为刷新
     */
    private void getFriendsSkillList(final boolean isRefresh) {
        Map<String, String> map = new HashMap<>();
        map.put("page", currentPager + "");
        map.put("count", pageSize + "");
        map.put("skillid", cat_id);
        map.put("attribute", "1");
        DataManager dataManager = new DataManager();
        ObserverOnNextListener<List<UserBean>> listener = new ObserverOnNextListener<List<UserBean>>() {
            @Override
            public void onNext(List<UserBean> detailBeanList) {
                currentPager++;
                if (isRefresh) {
                    adapter.setNewData(detailBeanList);
                    refreshLayout.finishRefresh();
                } else {
                    adapter.addData(detailBeanList);
                    refreshLayout.finishLoadMore();
                    if (detailBeanList.size() < pageSize) {
                        refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                    }
                }
            }
        };
        dataManager.friendsSkillList(new ProgressObserver<List<UserBean>>(listener, this) {
            @Override
            public void showDialog() {
            }
        }, map);

    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishLoadMore(5000);
        if ("Around".equals(origin))
        {
            getAround4skill(false);
        }
        else if ("Friends".equals(origin))
        {
            getFriendsSkillList(false);
        }
        else
        {
            getFriendsList(false);
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishRefresh(5000);
        currentPager = 1;
        if ("Around".equals(origin))
        {
            getAround4skill(true);
        }
        else if ("Friends".equals(origin))
        {
            getFriendsSkillList(true);
        }
        else
        {
            getFriendsList(true);
        }
        refreshLayout.setNoMoreData(false);
    }


    @OnClick({R.id.iv_back, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_confirm://编辑/删除

                if ("Around".equals(origin)||"Friends".equals(origin)) {
                    List<String> userIdList = adapter.getUserIdList();
                    if (userIdList.size()>0) {
                        String userList="" ;
                        for (String s : userIdList) {
                            userList = userList + s+",";
                        }
                        Intent intent = new Intent();
                        intent.putExtra("userList",userList.substring(0,userList.length()-1));
                        intent.putExtra("userCount",userIdList.size());
                        setResult(RESULT_OK,intent);
                        finish();
                    }
                    else
                    {
                        ToastUtils.show(MyFriendsActivity.this,"请选择用户");
                    }
                } else {
                    if ("编辑".equals(tvConfirm.getText().toString())) {
                        adapter.setShowSelecteView(true);
                        tvConfirm.setText("删除");
                    }else {
                        adapter.setShowSelecteView(false);
                        tvConfirm.setText("编辑");
                        List<String> userIdList = adapter.getUserIdList();
                        if (userIdList.size()>0) {
                            String userList="" ;
                            for (String s : userIdList) {
                                userList = userList + s+",";
                            }
                            deleteFriends(userList.substring(0,userList.length()-1));
                        }
                    }
                }

                break;
        }
    }
    /**
     * 移除好友
     */
    private void deleteFriends(String id) {
        DataManager dataManager = new DataManager();
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object data) {

            }
        };
        dataManager.deletefriend(new ProgressObserver<Object>(listener,this),id);
    }

    private void getAround4skill(final boolean isRefresh)
    {
        Map<String, String> map = new HashMap<>();
        map.put("page", currentPager + "");
        map.put("count", pageSize + "");
        map.put("skillid", cat_id);
        map.put("lat", latitude +"");
        map.put("lon", longitude+"");
        DataManager dataManager = new DataManager();
        ObserverOnNextListener<List<UserBean>> listener = new ObserverOnNextListener<List<UserBean>>() {
            @Override
            public void onNext(List<UserBean> detailBeanList) {
                currentPager++;
                if (isRefresh) {
                    adapter.setNewData(detailBeanList);
                    refreshLayout.finishRefresh();
                } else {
                    adapter.addData(detailBeanList);
                    refreshLayout.finishLoadMore();
                    if (detailBeanList.size() < pageSize) {
                        refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                    }
                }
            }
        };
        dataManager.getAround4skill(new ProgressObserver<List<UserBean>>(listener, this) {
            @Override
            public void showDialog() {
            }
        }, map);
    }
}
